package com.example.gbuffer.RenderPass;

import android.content.Context;
import android.opengl.GLES32;
import android.opengl.Matrix;
import android.util.Log;

import com.example.gbuffer.Component.Camera.PerspectiveCamera;
import com.example.gbuffer.Component.Framebuffer.Framebuffer;
import com.example.gbuffer.Component.Light.Light;
import com.example.gbuffer.Component.Light.PointLight;
import com.example.gbuffer.Component.Model.CubeModel;
import com.example.gbuffer.Component.Shader;

import javax.microedition.khronos.opengles.GL;

public class LightCubeRenderPass extends RenderPass{

    private final static Shader m_shader = new Shader();
    public static PerspectiveCamera m_camera_p = new PerspectiveCamera();
    public static CubeModel m_cube = new CubeModel();
    private static Light[] m_light_list = new Light[2];

    private static float[] m_modelMatrix = new float[16];

    public LightCubeRenderPass(Framebuffer buffer) {
        super(buffer);

        addDrawCalls();
    }

    public void setLights(Light[] lights) {
        m_light_list = new Light[lights.length];
        System.arraycopy(lights, 0, m_light_list, 0, lights.length);
    }


    public void setPerspectiveCamera(PerspectiveCamera camera) {
        m_camera_p = camera;
    }

    public void initResources(Context ctx) {

        // 加载模型数据
        m_cube.load();

        // 生成并编译着色器
        m_shader.setName("LightCubeShader");
        m_shader.makeShaderProgramFromAssets(ctx, "light_cube_pass.vs", "light_cube_pass.fs");
    }

    public void addDrawCalls() { super.addDrawCall(LightCubeRenderPass::drawCube);}

    private static Integer drawCube() {

        GLES32.glEnable(GLES32.GL_DEPTH_TEST);

        m_shader.use();

        // 设置视图矩阵
        m_shader.setUniformMatrix4fv("u_ViewMatrix",
                m_camera_p.getLookAt());

        // 设置投影矩阵
        m_shader.setUniformMatrix4fv("u_ProjMatrix",
                m_camera_p.project());

        for(Light light : m_light_list) {

            // 设置模型矩阵
            float[] lightPos = light.getPosition();
            Matrix.setIdentityM(m_modelMatrix, 0);
            Matrix.translateM(m_modelMatrix, 0, lightPos[0], lightPos[1], lightPos[2]);
            Matrix.scaleM(m_modelMatrix, 0, 0.2f, 0.2f, 0.2f);
            m_shader.setUniformMatrix4fv("u_ModelMatrix", m_modelMatrix);

            // 设置光源颜色 uniform
            m_shader.setUniform3fv("u_lightColor", light.getLightColor());

            m_cube.draw(m_shader);
        }

        return 0;
    }
}
